﻿using System;

namespace Netbits.Common.Logging.Handler
{
	/// <summary>
	/// Represents a console log-handler
	/// </summary>
	public sealed class ConsoleLogHandler : ILogHandler
	{
		#region Private Variables

		int _PrintGroupNames;

		#endregion

		#region Public Properties

		/// <summary>
		/// Get or sets if the group-names a print on the console.
		/// </summary>
		public bool PrintGroupNames
		{
			get
			{
				return (_PrintGroupNames == 1);
			}
			set
			{
				System.Threading.Interlocked.Exchange( ref _PrintGroupNames, (value ? 1 : 0) );
			}
		}

		#endregion

		#region ILogHandler

		/// <summary>
		/// Returns if the Logs are synchronous handled. 
		/// This property returns always true
		/// </summary>
		public bool HandleSync
		{
			get
			{
				return true;
			}
		}

		/// <summary>
		/// Process the log-entry.
		/// </summary>
		/// <param name="Log_">The LogEntry to process</param>
		public void ProcessLog( LogEntry Log_ )
		{
			DateTime dt = new DateTime( Log_.Ticks );

			string msg = string.Format( "{0:0000}.{1:00}.{2:00} ", dt.Year, dt.Month, dt.Day );
			msg += string.Format( "{0:00}:{1:00}:{2:00}.{3:000} ", dt.Hour, dt.Minute, dt.Second, dt.Millisecond );
			msg += string.Format( "{0,-7}", Log_.Type.ToString() );
			if( _PrintGroupNames > 0 )
				msg += string.Format( "[{0, -10}] ", Log_.Group.Name );
			msg += Log_.Message;

			switch( Log_.Type )
			{
				case LogType.Debug:
					Console.ForegroundColor = ConsoleColor.Gray;
					Console.WriteLine( msg );
					break;
				case LogType.Error:
					Console.ForegroundColor = ConsoleColor.DarkRed;
					Console.WriteLine( msg );
					break;
				case LogType.Fatal:
					Console.ForegroundColor = ConsoleColor.Red;
					Console.WriteLine( msg );
					break;
				case LogType.Info:
					Console.ResetColor();
					Console.WriteLine( msg );
					break;
				case LogType.Warning:
					Console.ForegroundColor = ConsoleColor.Yellow;
					Console.WriteLine( msg );
					break;
			}
		}

		#endregion
	}
}
